#include "NeoSwitchButton.h"
#include "private/NeoSwitchButtonPrivate.h"
#include <QMouseEvent>
#include <QPropertyAnimation>

NEO_PUBLIC_PROPERTY_CREATE_NOTIFY_CPP(NeoSwitchButton, bool, Checked)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoSwitchButton, QColor, IndicatorCheckedColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoSwitchButton, QColor, IndicatorUncheckedColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoSwitchButton, QColor, BackgroundCheckedColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoSwitchButton, QColor, BackgroundUncheckedColor)

NeoSwitchButton::NeoSwitchButton(QWidget *parent)
    : QWidget(parent), d_ptr(new NeoSwitchButtonPrivate())
{
    NEO_PUBLIC_POINT(NeoSwitchButton)
    d->q_ptr = this;
    connect(d->pPositionAnimation, &QPropertyAnimation::valueChanged, this, [this]()
            { this->update(); });
    connect(d->pPositionAnimation, &QPropertyAnimation::finished, this, [this]()
            {NEO_PUBLIC_POINT(NeoSwitchButton)
              this->setChecked(!d->pChecked); });
}

NeoSwitchButton::~NeoSwitchButton() = default;

void NeoSwitchButton::mousePressEvent(QMouseEvent *event)
{
    NEO_PUBLIC_POINT(NeoSwitchButton)
    if (event->button() == Qt::LeftButton)
    {
        d->startPositionAnimation();
        event->accept();
        return;
    }
    return QWidget::mousePressEvent(event);
}

void NeoSwitchButton::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        event->accept();
        return;
    }
    return QWidget::mouseReleaseEvent(event);
}

void NeoSwitchButton::resizeEvent(QResizeEvent *event)
{
    NEO_PUBLIC_POINT(NeoSwitchButton)
    d->updateWidgetGeometry(event->size());
    return QWidget::resizeEvent(event);
}

void NeoSwitchButton::paintEvent(QPaintEvent *event)
{
    NEO_PUBLIC_POINT(NeoSwitchButton)
    NEO_PAINTER_RESET
    d->drawBackground(&painter);
    d->drawIndicator(&painter);
}